﻿using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Text;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Security.Cryptography;
using System.Data.SqlClient;
using Microsoft.ApplicationBlocks.Data;
using AnyOffice.DAL;
using  AnyOffice.Components ;

namespace AnyOffice
{
    public partial class login : Page
    {
        public bool loginKey;



        private byte[] getBytes(string HexStr)
        {
            string str = "0123456789ABCDEF";
            string str2 = HexStr.ToUpper();
            int length = str2.Length;
            byte[] buffer = new byte[length / 2];
            for (int i = 0; i < (length / 2); i++)
            {
                int index = str.IndexOf(str2[i * 2]);
                int num4 = str.IndexOf(str2[(i * 2) + 1]);
                buffer[i] = Convert.ToByte((int)((index * 16) + num4));
            }
            return buffer;
        }


        private string GetMD5(string str)
        {
            byte[] bytes = Encoding.GetEncoding(1252).GetBytes(str);//////////////////////////
            bytes = new MD5CryptoServiceProvider().ComputeHash(bytes);
            string str2 = "";
            for (int i = 0; i < bytes.Length; i++)
            {
                str2 = str2 + bytes[i].ToString("x").PadLeft(2, '0');
            }
            return str2;
        }
        private void GetMessage(string message)
        {
            this.litMessage.Text = message;
            StringBuilder builder = new StringBuilder();
            builder.Append("<script type=\"text/javascript\" language=\"javascript\">\n");
            builder.Append("if(popMessage){alert('" + message + "');}\n");
            builder.Append("</script>\n");

           // this.Page.RegisterStartupScript("pop", builder.ToString());

            ClientScript.RegisterStartupScript(this.GetType(), "pop", builder.ToString());
        }


        private void UserLogin(string userId, string password, bool loginKey, bool securityVerifyCode, string verifyCode, bool securityRember)
        {
            if (securityVerifyCode)
            {
                if (this.Session["VerifyCode"] == null)
                {
                    this.GetMessage("验证码错误！");
                    return;
                }
                if (verifyCode != this.Session["VerifyCode"].ToString())
                {
                    this.GetMessage("验证码错误！");
                    return;
                }
            }
            string str = string.Empty;
            string str2 = string.Empty;
            bool flag = false;
            string str3 = string.Empty;
            SqlConnection conn = new SqlConnection(ConfigManager.ConnectionString);
            if ((this.UGuid.Value != string.Empty) && (this.UDigest.Value != string.Empty))
            {
                string str4 = this.Session["RandomStr"].ToString();
                string str5 = this.UDigest.Value;
                string str6 = this.UGuid.Value;
                string str7 = "";
                string commandText = "SELECT [UserId],[MenuType],[BindIp],[UKey],[Disabled] FROM [dbo].[Users] WHERE [UGuid]=@UGuid AND [UKey] IS NOT NULL";
                SqlParameter[] commandParameters = new SqlParameter[] { new SqlParameter("@UGuid", SqlDbType.NVarChar, 50) };
                commandParameters[0].Value = str6;
                DataTable table = SqlHelper.ExecuteDataset(ConfigManager.ConnectionString, CommandType.Text, commandText, commandParameters).Tables[0];

                if (table.Rows.Count <= 0)
                {
                    SysLog.Log(conn, userId, 17, "USB KEY帐户不存在");
                    this.GetMessage("USB KEY帐户不存在！");
                    return;
                }
                str7 = this.GetMD5(str4 + table.Rows[0]["UKey"].ToString());
                if (str5 != str7)
                {
                    SysLog.Log(conn, userId, 17, "USB KEY验证失败");
                    this.GetMessage("USB KEY验证失败，请插入合法的认证钥匙！");
                    return;
                }
                if (Convert.ToBoolean(table.Rows[0]["Disabled"].ToString()))
                {
                    SysLog.Log(conn, table.Rows[0]["UserId"].ToString(), 16, "用户KEY验证,帐号已禁用");
                    this.GetMessage("帐号已禁用！");
                    return;
                }
                flag = Convert.ToBoolean(table.Rows[0]["MenuType"].ToString());
                if (table.Rows[0]["BindIp"] != DBNull.Value)
                {
                    str3 = table.Rows[0]["BindIp"].ToString();
                }
                str = table.Rows[0]["UserId"].ToString();
                commandText = "UPDATE [dbo].[Users] SET [LastVisitTime] = getdate(), [LastPassTime] = getdate(), [State] = 1 WHERE [UserId]= @UserId ";
                commandParameters[0] = new SqlParameter("@UserId", SqlDbType.NVarChar, 20);
                commandParameters[0].Value = str;
                SqlHelper.ExecuteNonQuery(conn, CommandType.Text, commandText, commandParameters);
            }
            if (str == string.Empty)
            {
                DataTable table2 = new UsersDao().Login(conn, userId, password);
                if (table2.Rows.Count <= 0)
                {
                    SysLog.Log(conn, userId, 2, "");
                    this.GetMessage("用户名或密码错误！");
                    return;
                }
                str2 = table2.Rows[0]["UserId"].ToString();
                flag = Convert.ToBoolean(table2.Rows[0]["MenuType"].ToString());
                if (table2.Rows[0]["BindIp"] != DBNull.Value)
                {
                    str3 = table2.Rows[0]["BindIp"].ToString();
                }
                if (Convert.ToBoolean(table2.Rows[0]["Disabled"].ToString()))
                {
                    SysLog.Log(conn, userId, 16, "");
                    this.GetMessage("帐号已禁用！");
                    return;
                }
                if (loginKey && Convert.ToBoolean(table2.Rows[0]["UsingKey"].ToString()))
                {
                    SysLog.Log(conn, userId, 17, "用户KEY验证失败");
                    this.GetMessage("用户KEY验证失败，请插入合法的认证钥匙！");
                    return;
                }
            }
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
            }
            if (str != string.Empty)
            {
                userId = str;
            }
            else
            {
                userId = str2;
            }
            if ((str3 != string.Empty) && (str3.IndexOf(Request.UserHostAddress) == -1))
            {
                SysLog.Log(conn, userId, 9, "");
                this.GetMessage("非法IP登录！");
            }
            else
            {
                SysLog.Log(conn, userId, 1, "");
                FormsAuthentication.SetAuthCookie(userId, true);
                if (securityRember)
                {
                    HttpCookie cookie = new HttpCookie("AnyOffice_Rember_UserId", Server.UrlEncode(userId));
                    cookie.Expires = DateTime.Now.AddMonths(1);
                    Response.Cookies.Add(cookie);
                }
                UserCache.Update(userId);
                if (flag)
                {
                    this.pnlMain.Visible = false;
                    this.litPromat.Text = "<div class=big1>正在进入OA系统，请稍候...</div>";
                    StringBuilder builder = new StringBuilder();
                    builder.Append("<script>\n");
                    builder.Append("function goto_oa()\n");
                    builder.Append("{\n");
                    builder.Append("\tlocation=\"general/index.aspx\";\n");
                    builder.Append("}\n");
                    builder.Append("if(window.name == \"oa_main\")\n");
                    builder.Append("\tlocation=\"general/index.aspx\";");
                    builder.Append("else\n");
                    builder.Append("{\n");
                    builder.Append("\tvar open_flag=window.open(\"general/index.aspx\",'oa_main',\"menubar=0,toolbar=0,status=1,resizable=1\");\n");
                    builder.Append("\tif(open_flag== null)\n");
                    builder.Append("\t\tgoto_oa();\n");
                    builder.Append("\telse\n");
                    builder.Append("\t{\n");
                    builder.Append("\twindow.opener = window.self;\n");
                    builder.Append("\twindow.close();\n");
                    builder.Append("\t}\n");
                    builder.Append("}\n");
                    builder.Append("</script>\n");

                    if (!ClientScript.IsStartupScriptRegistered("gotooa"))
                    {
                        //this.Page.RegisterStartupScript("gotooa", builder.ToString());
                        ClientScript.RegisterStartupScript(this.GetType(), "gotooa", builder.ToString());
                    }
                }
                else
                {
                    Response.Redirect("general/index.aspx");
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.litTitle.InnerText = InterfaceCache.StatusText;
            ConfigManager manager = new ConfigManager();
            this.loginKey = manager.LoginKey;
            string userId = string.Empty;
            string password = string.Empty;
            string verifyCode = string.Empty;
            if (!this.Page.IsPostBack)
            {
                Response.AppendHeader("Expires", DateTime.Now.AddDays(-1.0).ToString("r"));
                Response.AppendHeader("Pragma", "no-cache");
                Response.AppendHeader("Cache-Control", "no-cache");
                Random random = new Random(DateTime.Now.Millisecond);
                string str6 = "";
                for (int i = 0; i < 32; i++)
                {
                    str6 = str6 + Convert.ToChar(random.Next(97, 122));
                }
                this.Session["RandomStr"] = str6;
                if (Request.Form["userid"] != null)
                {
                    userId = Request.Form["userid"].ToString().ToLower();
                    this.txtUserId.Value = userId;
                    if (Request.Form["password"] != null)
                    {
                        password = Request.Form["password"].ToString();
                    }
                    if (Request.Form["verifycode"] != null)
                    {
                        verifyCode = Request.Form["verifycode"].ToString().ToUpper();
                    }
                    password = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "md5");
                    this.UserLogin(userId, password, manager.LoginKey, manager.SecurityVerifyCode, verifyCode, manager.SecurityRember);
                }
                else if (manager.SecurityRember && (Request.Cookies["AnyOffice_Rember_UserId"] != null))
                {
                    this.txtUserId.Value = Server.UrlDecode(Request.Cookies["AnyOffice_Rember_UserId"].Value);
                }
                if (manager.SecurityVerifyCode)
                {
                    //this.litVerifyCode.Text = "<img id=\"imgVerifyCode\" onclick=\"this.src='validate_code.aspx';\" src=\"validate_code.aspx\" alt=\"验证码，看不清楚？请点击刷新验证码\" align=\"AbsMiddle\" border=\"0\" style=\"cursor: pointer\">";
                    //this.pnlVerifyCode.Visible = true;
                }
            }
            if (this.Page.IsPostBack)
            {
                userId = this.txtUserId.Value.ToLower();
                password = FormsAuthentication.HashPasswordForStoringInConfigFile(this.txtPassword.Value, "md5");
                //verifyCode = this.txtVerifyCode.Value.ToUpper();
                this.UserLogin(userId, password, manager.LoginKey, manager.SecurityVerifyCode, verifyCode, manager.SecurityRember);
            }

        }




    }
}
